# pylint: disable-msg=E1101
"""
@author: Sergiy Tsymbalyuk
"""

import logging
from datetime import datetime

from pylons import url, request, response, tmpl_context as c, session
from pylons.controllers.util import redirect

from chowa.lib.base import BaseController, render, Session
from chowa.model.auth import User

log = logging.getLogger(__name__)


class AuthController(BaseController):
    """Authorization system."""
    
    def login(self):
        c.came_from = str(request.params.get('came_from', '')) or url('/')
        return render('/auth/login_page.html')
    
    def logout(self):
        # offline status
        user_id = session.get('user_id')
        user = Session.query(User).get(user_id)
        user.is_online = False
        Session.add(user)
        Session.commit()
        
        came_from = str(request.params.get('came_from', '')) or url('/')
        return redirect(came_from)
    
    def welcome(self):
        identity = request.environ.get('repoze.who.identity')
        came_from = str(request.params.get('came_from', '')) or url('/')
        if not identity:
            return redirect(url(controller='site/auth', action='login'))
        # Save user id in session for logout handling 
        session['user_id'] = identity['user'].id
        session.save()
        # Write last login time
        user = identity['user']
        user.last_login = datetime.now()
        Session.add(user)
        Session.commit()
        # Continue cookie expire time
        authtkt = request.cookies['authtkt']
        response.set_cookie('authtkt', authtkt, max_age=60*60*24*7, path='/')
        
        return redirect(came_from)
